/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package composite.number_expression.fact;

import composite.Component;
import composite.number_expression.Fact;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import visitor.Visitor;

/**
 *
 * @author Antonio
 */
public class FactId extends Fact {

    private String id;
    private int num;

    public FactId(String id) {

        this.id = id;
        num = 0;
    }

    public int getStato() {

        return num;
    }// getStato

    @Override
    public void interpreta(String contesto) {

        File f = new File(contesto);

        try {

            BufferedReader in = new BufferedReader(new FileReader(f));
            String linea;

            while (true) {

                try {

                    linea = in.readLine();

                    if (linea == null) {// condizione uscita dal while

                        in.close();
                        break;
                    }

                    StringTokenizer st = new StringTokenizer(linea, "=");
                    String temp;

                    while (st.hasMoreTokens()) {

                        temp = st.nextToken();

                        if (id.equalsIgnoreCase(temp)) {// valore di factId

                            num = (Integer.parseInt(st.nextToken()));
                            break;
                        }

                    }


                } catch (IOException ex) {

                    System.out.println("Attezione, si e' verificato un errore di lettura.");
                    in.close();
                    System.exit(-1);
                }

            }

            in.close();
        } catch (FileNotFoundException ex) {

            System.out.println("Attenzione, file " + contesto + " non trovato.");
            System.exit(-1);
        } catch (IOException ex) {

            System.out.println("Attenzione, lettura interrotta");
            System.exit(-1);
        }
    }

    @Override
    public void accept(Visitor v) {

        v.visit(this);
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();

        return sb.append(num).toString();
    }

    @Override
    public void add(Component c) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
